package com.lagou.service;

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.OSSObject;
import com.lagou.bean.Result;
import com.lagou.bean.UpLoadResult;
import com.lagou.config.AliyunConfig;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.UUID;

/**
 * @author zjy
 */
@Service
@Slf4j
public class OSSService {

    @Autowired
    private AliyunConfig aliyunConfig;

    @Autowired
    private OSSClient ossClient;

    /**
     * 允许上传的格式
     */
    private static final String[] IMAGE_TYPE = new String[]{".jpg",
            ".jpeg", ".png","md"};

    /**
     * @param multipartFile
     * @return
     */
    public UpLoadResult upload(MultipartFile multipartFile) {
        long size = multipartFile.getSize();
        long maxSize = 10*1024*1024;
        UpLoadResult upLoadResult = new UpLoadResult();
        //校验文件大小
        if(size > maxSize){
            upLoadResult.setStatus("文件大小不能超过10m");
            return upLoadResult;
        }
        // 校验图片格式
        boolean isLegal = false;
        for (String type : IMAGE_TYPE) {
            if (StringUtils.endsWithIgnoreCase(multipartFile.getOriginalFilename(), type)) {
                isLegal = true;
                break;
            }
        }
        if (!isLegal) {
            upLoadResult.setStatus("file type error");
            return upLoadResult;
        }
        String fileName = multipartFile.getOriginalFilename();
        String filePath = getFilePath(fileName);
        try {
            ossClient.putObject(aliyunConfig.getBucketName(), filePath, new ByteArrayInputStream(multipartFile.getBytes()));
        } catch (IOException e) {
            e.printStackTrace();
            // 上传失败
            upLoadResult.setStatus("error");
            return upLoadResult;
        }
        upLoadResult.setStatus("done");
        upLoadResult.setName(aliyunConfig.getUrlPrefix() + filePath);
        upLoadResult.setUid(filePath);
        return upLoadResult;
    }

    /**
     * 生成不重复的文件路径和文件名
     */
    private String getFilePath(String sourceFileName) {
        DateTime dateTime = new DateTime();
        return "images/" + dateTime.toString("yyyy")
                + "/" + dateTime.toString("MM") + "/"
                + dateTime.toString("dd") + "/" + UUID.randomUUID().toString() + "." +
                StringUtils.substringAfterLast(sourceFileName, ".");
    }

    public Result download(String uid, HttpServletResponse response) {


        try {
            String bucketName = aliyunConfig.getBucketName();
            OSSObject ossObject = ossClient.getObject(bucketName, uid);
            int buffer = 1024 * 10;
            byte data[] = new byte[buffer];
            if (ossObject != null) {
                InputStream inputStream = ossObject.getObjectContent();
                try {
                    // 文件名可以任意指定
                    response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(uid, "UTF-8"));//将文件名转为ASCLL编码
                    int read;
                    while ((read = inputStream.read(data)) != -1) {
                        response.getOutputStream().write(data, 0, read);
                    }
                    response.getOutputStream().flush();
                    response.getOutputStream().close();
                    ossObject.close();
                } catch (UnsupportedEncodingException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                return null;
            }
            return Result.error("文件名不存在");
        } catch (Exception e) {
            OSSException ee = (OSSException) e;
            e.printStackTrace();
            log.error("eee >>>>{}", ee.getErrorMessage());
            return Result.error(ee.getErrorMessage());
        }
    }

    public Result delete(String uid) {
        String bucketName = aliyunConfig.getBucketName();
        ossClient.deleteObject(bucketName, uid);
        return Result.ok();
    }

}
